{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "# 含并行连结的网络（GoogLeNet）\n",
    "\n",
    "在2014年的ImageNet图像识别挑战赛中，一个名叫GoogLeNet的网络结构大放异彩 [1]。它虽然在名字上向LeNet致敬，但在网络结构上已经很难看到LeNet的影子。GoogLeNet吸收了NiN中网络串联网络的思想，并在此基础上做了很大改进。在随后的几年里，研究人员对GoogLeNet进行了数次改进，本节将介绍这个模型系列的第一个版本。\n",
    "\n",
    "\n",
    "## Inception 块\n",
    "\n",
    "GoogLeNet中的基础卷积块叫作Inception块，得名于同名电影《盗梦空间》（Inception）。与上一节介绍的NiN块相比，这个基础块在结构上更加复杂，如图5.8所示。\n",
    "\n",
    "![Inception块的结构](../img/inception.svg)\n",
    "\n",
    "由图5.8可以看出，Inception块里有4条并行的线路。前3条线路使用窗口大小分别是$1\\times 1$、$3\\times 3$和$5\\times 5$的卷积层来抽取不同空间尺寸下的信息，其中中间2个线路会对输入先做$1\\times 1$卷积来减少输入通道数，以降低模型复杂度。第四条线路则使用$3\\times 3$最大池化层，后接$1\\times 1$卷积层来改变通道数。4条线路都使用了合适的填充来使输入与输出的高和宽一致。最后我们将每条线路的输出在通道维上连结，并输入接下来的层中去。\n",
    "\n",
    "Inception块中可以自定义的超参数是每个层的输出通道数，我们以此来控制模型复杂度。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import paddle\r\n",
    "import paddle.nn as nn\r\n",
    "import numpy as np\r\n",
    "\r\n",
    "class Inception(nn.Layer):\r\n",
    "    # c1 - c4为每条线路里的层的输出通道数\r\n",
    "    def __init__(self, num_channels, c1, c2, c3, c4):\r\n",
    "        super(Inception, self).__init__()\r\n",
    "        # 线路1，单1 x 1卷积层\r\n",
    "        p1 = [\r\n",
    "            nn.Conv2D(num_channels, c1, 1),\r\n",
    "            nn.ReLU()\r\n",
    "        ]\r\n",
    "        self.p1 = nn.Sequential(*p1)\r\n",
    "        # 线路2，1 x 1卷积层后接3 x 3卷积层\r\n",
    "        p2 = [\r\n",
    "            nn.Conv2D(num_channels, c2[0], 1),\r\n",
    "            nn.ReLU(),\r\n",
    "            nn.Conv2D(c2[0], c2[1], 3, padding=1),\r\n",
    "            nn.ReLU()\r\n",
    "        ]\r\n",
    "        self.p2 = nn.Sequential(*p2)\r\n",
    "        # 线路3，1 x 1卷积层后接5 x 5卷积层\r\n",
    "        p3 = [\r\n",
    "            nn.Conv2D(num_channels, c3[0], 1),\r\n",
    "            nn.ReLU(),\r\n",
    "            nn.Conv2D(c3[0], c3[1], 5, padding=2),\r\n",
    "            nn.ReLU()\r\n",
    "        ]\r\n",
    "        self.p3 = nn.Sequential(*p3)\r\n",
    "        # 线路4，3 x 3最大池化层后接1 x 1卷积层\r\n",
    "        p4 = [\r\n",
    "            nn.MaxPool2D(3, stride=1, padding=1),\r\n",
    "            nn.Conv2D(num_channels, c4, 1),\r\n",
    "            nn.ReLU()\r\n",
    "        ]\r\n",
    "        self.p4 = nn.Sequential(*p4)\r\n",
    "    def forward(self, X):\r\n",
    "        # 在通道维上连结输出\r\n",
    "        return paddle.concat([self.p1(X), self.p2(X), self.p3(X), self.p4(X)], axis=1)\r\n",
    "\r\n",
    "# with paddle.fluid.dygraph.guard():\r\n",
    "#     incep = Inception(3, 64, (96, 128), (16, 32), 32)\r\n",
    "#     X = paddle.to_tensor(np.random.uniform(-1, 1, [1, 3, 28, 28]).astype('float32'))\r\n",
    "#     Y = incep(X)\r\n",
    "#     print(Y.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## GoogLeNet模型\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 10]\n"
     ]
    }
   ],
   "source": [
    "class GoogleNet(nn.Layer):\r\n",
    "    def __init__(self, num_classes=10):\r\n",
    "        super(GoogleNet, self).__init__()\r\n",
    "        # GoogLeNet跟VGG一样，在主体卷积部分中使用5个模块（block），\r\n",
    "        # 个模块之间使用步幅为2的3×3最大池化层来减小输出高宽。\r\n",
    "        # 第一模块使用一个64通道的7×7卷积层。\r\n",
    "        model = [\r\n",
    "            nn.Conv2D(1, 64, 7, stride=2, padding=3),\r\n",
    "            nn.ReLU(),\r\n",
    "            nn.MaxPool2D(3, stride=2, padding=1)\r\n",
    "        ]\r\n",
    "        # 第二模块使用2个卷积层：首先是64通道的1×1卷积层，\r\n",
    "        # 然后是将通道增大3倍的3×3卷积层。\r\n",
    "        # 它对应Inception块中的第二条线路。\r\n",
    "        # model += [\r\n",
    "        #     nn.Conv2D(64, 64, 1),\r\n",
    "        #     nn.ReLU(),\r\n",
    "        #     nn.Conv2D(64, 192, 3, padding=1),\r\n",
    "        #     nn.ReLU(),\r\n",
    "        #     nn.MaxPool2D(3, stride=2, padding=1)\r\n",
    "        # ]\r\n",
    "        # 第三模块串联2个完整的Inception块。\r\n",
    "        # 第一个Inception块的输出通道数为64+128+32+32=256，\r\n",
    "        # 其中4条线路的输出通道数比例为64:128:32:32=2:4:1:1。\r\n",
    "        # 其中第二、第三条线路先分别将输入通道数减小至96/192=1/2和16/192=1/12后，再接上第二层卷积层。\r\n",
    "        # 第二个Inception块输出通道数增至128+192+96+64=480，\r\n",
    "        # 每条线路的输出通道数之比为128:192:96:64=4:6:3:2。\r\n",
    "        # 其中第二、第三条线路先分别将输入通道数减小至128/256=1/2和32/256=1/8。\r\n",
    "        model += [\r\n",
    "            Inception(64, 64, (96, 128), (16, 32), 32),\r\n",
    "            # Inception(192, 64, (96, 128), (16, 32), 32),\r\n",
    "            Inception(256, 128, (128, 192), (32, 96), 64),\r\n",
    "            nn.MaxPool2D(3, stride=2, padding=1)\r\n",
    "        ]\r\n",
    "        # 第四模块更加复杂。它串联了5个Inception块，\r\n",
    "        # 其输出通道数分别是192+208+48+64=512、160+224+64+64=512、\r\n",
    "        # 128+256+64+64=512、112+288+64+64=528528和256+320+128+128=832。\r\n",
    "        # 这些线路的通道数分配和第三模块中的类似，\r\n",
    "        # 首先是含3×3卷积层的第二条线路输出最多通道，\r\n",
    "        # 其次是仅含1×1卷积层的第一条线路，\r\n",
    "        # 之后是含5×5卷积层的第三条线路和含3×3最大池化层的第四条线路。\r\n",
    "        # 其中第二、第三条线路都会先按比例减小通道数。\r\n",
    "        # 这些比例在各个Inception块中都略有不同。\r\n",
    "        model += [\r\n",
    "            Inception(480, 192, (96, 208), (16, 48), 64),\r\n",
    "            Inception(512, 160, (112, 224), (24, 64), 64),\r\n",
    "            Inception(512, 128, (128, 256), (24, 64), 64),\r\n",
    "            Inception(512, 112, (144, 288), (32, 64), 64),\r\n",
    "            Inception(528, 256, (160, 320), (32, 128), 128),\r\n",
    "            nn.MaxPool2D(3, stride=2, padding=1)\r\n",
    "        ]\r\n",
    "        # 第五模块有输出通道数为256+320+128+128=832和384+384+128+128=1024的两个Inception块。\r\n",
    "        # 其中每条线路的通道数的分配思路和第三、第四模块中的一致，只是在具体数值上有所不同。\r\n",
    "        # 需要注意的是，第五模块的后面紧跟输出层，该模块同NiN一样使用全局平均池化层来将每个通道的高和宽变成1。\r\n",
    "        # 最后我们将输出变成二维数组后接上一个输出个数为标签类别数的全连接层。\r\n",
    "        model += [\r\n",
    "            Inception(832, 256, (160, 320), (32, 128), 128),\r\n",
    "            Inception(832, 384, (192, 384), (48, 128), 128),\r\n",
    "            paddle.fluid.dygraph.Pool2D(pool_type='max', global_pooling=True)\r\n",
    "        ]\r\n",
    "        self.model = nn.Sequential(*model)\r\n",
    "        self.fc = nn.Sequential(nn.Linear(1024, 10))\r\n",
    "    def forward(self, X):\r\n",
    "        Y = self.model(X)\r\n",
    "        Y = paddle.flatten(Y, start_axis=1)\r\n",
    "        Y = self.fc(Y)\r\n",
    "        return Y\r\n",
    "\r\n",
    "with paddle.fluid.dygraph.guard():\r\n",
    "    googlenet = GoogleNet()\r\n",
    "    X = paddle.to_tensor(np.random.uniform(-1, 1, [1, 1, 28, 28]).astype('float32'))\r\n",
    "    Y = googlenet(X)\r\n",
    "    print(Y.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "GoogLeNet模型的计算复杂，而且不如VGG那样便于修改通道数。本节里我们将输入的高和宽从224降到96来简化计算。下面演示各个模块之间的输出的形状变化。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "---------------------------------------------------------------------------\n",
      " Layer (type)       Input Shape          Output Shape         Param #    \n",
      "===========================================================================\n",
      "   Conv2D-1       [[1, 1, 28, 28]]     [1, 64, 14, 14]         3,200     \n",
      "    ReLU-1       [[1, 64, 14, 14]]     [1, 64, 14, 14]           0       \n",
      "  MaxPool2D-1    [[1, 64, 14, 14]]      [1, 64, 7, 7]            0       \n",
      "   Conv2D-2       [[1, 64, 7, 7]]       [1, 64, 7, 7]          4,160     \n",
      "    ReLU-2        [[1, 64, 7, 7]]       [1, 64, 7, 7]            0       \n",
      "   Conv2D-3       [[1, 64, 7, 7]]       [1, 96, 7, 7]          6,240     \n",
      "    ReLU-3        [[1, 96, 7, 7]]       [1, 96, 7, 7]            0       \n",
      "   Conv2D-4       [[1, 96, 7, 7]]       [1, 128, 7, 7]        110,720    \n",
      "    ReLU-4        [[1, 128, 7, 7]]      [1, 128, 7, 7]           0       \n",
      "   Conv2D-5       [[1, 64, 7, 7]]       [1, 16, 7, 7]          1,040     \n",
      "    ReLU-5        [[1, 16, 7, 7]]       [1, 16, 7, 7]            0       \n",
      "   Conv2D-6       [[1, 16, 7, 7]]       [1, 32, 7, 7]         12,832     \n",
      "    ReLU-6        [[1, 32, 7, 7]]       [1, 32, 7, 7]            0       \n",
      "  MaxPool2D-2     [[1, 64, 7, 7]]       [1, 64, 7, 7]            0       \n",
      "   Conv2D-7       [[1, 64, 7, 7]]       [1, 32, 7, 7]          2,080     \n",
      "    ReLU-7        [[1, 32, 7, 7]]       [1, 32, 7, 7]            0       \n",
      "  Inception-1     [[1, 64, 7, 7]]       [1, 256, 7, 7]           0       \n",
      "   Conv2D-8       [[1, 256, 7, 7]]      [1, 128, 7, 7]        32,896     \n",
      "    ReLU-8        [[1, 128, 7, 7]]      [1, 128, 7, 7]           0       \n",
      "   Conv2D-9       [[1, 256, 7, 7]]      [1, 128, 7, 7]        32,896     \n",
      "    ReLU-9        [[1, 128, 7, 7]]      [1, 128, 7, 7]           0       \n",
      "   Conv2D-10      [[1, 128, 7, 7]]      [1, 192, 7, 7]        221,376    \n",
      "    ReLU-10       [[1, 192, 7, 7]]      [1, 192, 7, 7]           0       \n",
      "   Conv2D-11      [[1, 256, 7, 7]]      [1, 32, 7, 7]          8,224     \n",
      "    ReLU-11       [[1, 32, 7, 7]]       [1, 32, 7, 7]            0       \n",
      "   Conv2D-12      [[1, 32, 7, 7]]       [1, 96, 7, 7]         76,896     \n",
      "    ReLU-12       [[1, 96, 7, 7]]       [1, 96, 7, 7]            0       \n",
      "  MaxPool2D-3     [[1, 256, 7, 7]]      [1, 256, 7, 7]           0       \n",
      "   Conv2D-13      [[1, 256, 7, 7]]      [1, 64, 7, 7]         16,448     \n",
      "    ReLU-13       [[1, 64, 7, 7]]       [1, 64, 7, 7]            0       \n",
      "  Inception-2     [[1, 256, 7, 7]]      [1, 480, 7, 7]           0       \n",
      "  MaxPool2D-4     [[1, 480, 7, 7]]      [1, 480, 4, 4]           0       \n",
      "   Conv2D-14      [[1, 480, 4, 4]]      [1, 192, 4, 4]        92,352     \n",
      "    ReLU-14       [[1, 192, 4, 4]]      [1, 192, 4, 4]           0       \n",
      "   Conv2D-15      [[1, 480, 4, 4]]      [1, 96, 4, 4]         46,176     \n",
      "    ReLU-15       [[1, 96, 4, 4]]       [1, 96, 4, 4]            0       \n",
      "   Conv2D-16      [[1, 96, 4, 4]]       [1, 208, 4, 4]        179,920    \n",
      "    ReLU-16       [[1, 208, 4, 4]]      [1, 208, 4, 4]           0       \n",
      "   Conv2D-17      [[1, 480, 4, 4]]      [1, 16, 4, 4]          7,696     \n",
      "    ReLU-17       [[1, 16, 4, 4]]       [1, 16, 4, 4]            0       \n",
      "   Conv2D-18      [[1, 16, 4, 4]]       [1, 48, 4, 4]         19,248     \n",
      "    ReLU-18       [[1, 48, 4, 4]]       [1, 48, 4, 4]            0       \n",
      "  MaxPool2D-5     [[1, 480, 4, 4]]      [1, 480, 4, 4]           0       \n",
      "   Conv2D-19      [[1, 480, 4, 4]]      [1, 64, 4, 4]         30,784     \n",
      "    ReLU-19       [[1, 64, 4, 4]]       [1, 64, 4, 4]            0       \n",
      "  Inception-3     [[1, 480, 4, 4]]      [1, 512, 4, 4]           0       \n",
      "   Conv2D-20      [[1, 512, 4, 4]]      [1, 160, 4, 4]        82,080     \n",
      "    ReLU-20       [[1, 160, 4, 4]]      [1, 160, 4, 4]           0       \n",
      "   Conv2D-21      [[1, 512, 4, 4]]      [1, 112, 4, 4]        57,456     \n",
      "    ReLU-21       [[1, 112, 4, 4]]      [1, 112, 4, 4]           0       \n",
      "   Conv2D-22      [[1, 112, 4, 4]]      [1, 224, 4, 4]        226,016    \n",
      "    ReLU-22       [[1, 224, 4, 4]]      [1, 224, 4, 4]           0       \n",
      "   Conv2D-23      [[1, 512, 4, 4]]      [1, 24, 4, 4]         12,312     \n",
      "    ReLU-23       [[1, 24, 4, 4]]       [1, 24, 4, 4]            0       \n",
      "   Conv2D-24      [[1, 24, 4, 4]]       [1, 64, 4, 4]         38,464     \n",
      "    ReLU-24       [[1, 64, 4, 4]]       [1, 64, 4, 4]            0       \n",
      "  MaxPool2D-6     [[1, 512, 4, 4]]      [1, 512, 4, 4]           0       \n",
      "   Conv2D-25      [[1, 512, 4, 4]]      [1, 64, 4, 4]         32,832     \n",
      "    ReLU-25       [[1, 64, 4, 4]]       [1, 64, 4, 4]            0       \n",
      "  Inception-4     [[1, 512, 4, 4]]      [1, 512, 4, 4]           0       \n",
      "   Conv2D-26      [[1, 512, 4, 4]]      [1, 128, 4, 4]        65,664     \n",
      "    ReLU-26       [[1, 128, 4, 4]]      [1, 128, 4, 4]           0       \n",
      "   Conv2D-27      [[1, 512, 4, 4]]      [1, 128, 4, 4]        65,664     \n",
      "    ReLU-27       [[1, 128, 4, 4]]      [1, 128, 4, 4]           0       \n",
      "   Conv2D-28      [[1, 128, 4, 4]]      [1, 256, 4, 4]        295,168    \n",
      "    ReLU-28       [[1, 256, 4, 4]]      [1, 256, 4, 4]           0       \n",
      "   Conv2D-29      [[1, 512, 4, 4]]      [1, 24, 4, 4]         12,312     \n",
      "    ReLU-29       [[1, 24, 4, 4]]       [1, 24, 4, 4]            0       \n",
      "   Conv2D-30      [[1, 24, 4, 4]]       [1, 64, 4, 4]         38,464     \n",
      "    ReLU-30       [[1, 64, 4, 4]]       [1, 64, 4, 4]            0       \n",
      "  MaxPool2D-7     [[1, 512, 4, 4]]      [1, 512, 4, 4]           0       \n",
      "   Conv2D-31      [[1, 512, 4, 4]]      [1, 64, 4, 4]         32,832     \n",
      "    ReLU-31       [[1, 64, 4, 4]]       [1, 64, 4, 4]            0       \n",
      "  Inception-5     [[1, 512, 4, 4]]      [1, 512, 4, 4]           0       \n",
      "   Conv2D-32      [[1, 512, 4, 4]]      [1, 112, 4, 4]        57,456     \n",
      "    ReLU-32       [[1, 112, 4, 4]]      [1, 112, 4, 4]           0       \n",
      "   Conv2D-33      [[1, 512, 4, 4]]      [1, 144, 4, 4]        73,872     \n",
      "    ReLU-33       [[1, 144, 4, 4]]      [1, 144, 4, 4]           0       \n",
      "   Conv2D-34      [[1, 144, 4, 4]]      [1, 288, 4, 4]        373,536    \n",
      "    ReLU-34       [[1, 288, 4, 4]]      [1, 288, 4, 4]           0       \n",
      "   Conv2D-35      [[1, 512, 4, 4]]      [1, 32, 4, 4]         16,416     \n",
      "    ReLU-35       [[1, 32, 4, 4]]       [1, 32, 4, 4]            0       \n",
      "   Conv2D-36      [[1, 32, 4, 4]]       [1, 64, 4, 4]         51,264     \n",
      "    ReLU-36       [[1, 64, 4, 4]]       [1, 64, 4, 4]            0       \n",
      "  MaxPool2D-8     [[1, 512, 4, 4]]      [1, 512, 4, 4]           0       \n",
      "   Conv2D-37      [[1, 512, 4, 4]]      [1, 64, 4, 4]         32,832     \n",
      "    ReLU-37       [[1, 64, 4, 4]]       [1, 64, 4, 4]            0       \n",
      "  Inception-6     [[1, 512, 4, 4]]      [1, 528, 4, 4]           0       \n",
      "   Conv2D-38      [[1, 528, 4, 4]]      [1, 256, 4, 4]        135,424    \n",
      "    ReLU-38       [[1, 256, 4, 4]]      [1, 256, 4, 4]           0       \n",
      "   Conv2D-39      [[1, 528, 4, 4]]      [1, 160, 4, 4]        84,640     \n",
      "    ReLU-39       [[1, 160, 4, 4]]      [1, 160, 4, 4]           0       \n",
      "   Conv2D-40      [[1, 160, 4, 4]]      [1, 320, 4, 4]        461,120    \n",
      "    ReLU-40       [[1, 320, 4, 4]]      [1, 320, 4, 4]           0       \n",
      "   Conv2D-41      [[1, 528, 4, 4]]      [1, 32, 4, 4]         16,928     \n",
      "    ReLU-41       [[1, 32, 4, 4]]       [1, 32, 4, 4]            0       \n",
      "   Conv2D-42      [[1, 32, 4, 4]]       [1, 128, 4, 4]        102,528    \n",
      "    ReLU-42       [[1, 128, 4, 4]]      [1, 128, 4, 4]           0       \n",
      "  MaxPool2D-9     [[1, 528, 4, 4]]      [1, 528, 4, 4]           0       \n",
      "   Conv2D-43      [[1, 528, 4, 4]]      [1, 128, 4, 4]        67,712     \n",
      "    ReLU-43       [[1, 128, 4, 4]]      [1, 128, 4, 4]           0       \n",
      "  Inception-7     [[1, 528, 4, 4]]      [1, 832, 4, 4]           0       \n",
      " MaxPool2D-10     [[1, 832, 4, 4]]      [1, 832, 2, 2]           0       \n",
      "   Conv2D-44      [[1, 832, 2, 2]]      [1, 256, 2, 2]        213,248    \n",
      "    ReLU-44       [[1, 256, 2, 2]]      [1, 256, 2, 2]           0       \n",
      "   Conv2D-45      [[1, 832, 2, 2]]      [1, 160, 2, 2]        133,280    \n",
      "    ReLU-45       [[1, 160, 2, 2]]      [1, 160, 2, 2]           0       \n",
      "   Conv2D-46      [[1, 160, 2, 2]]      [1, 320, 2, 2]        461,120    \n",
      "    ReLU-46       [[1, 320, 2, 2]]      [1, 320, 2, 2]           0       \n",
      "   Conv2D-47      [[1, 832, 2, 2]]      [1, 32, 2, 2]         26,656     \n",
      "    ReLU-47       [[1, 32, 2, 2]]       [1, 32, 2, 2]            0       \n",
      "   Conv2D-48      [[1, 32, 2, 2]]       [1, 128, 2, 2]        102,528    \n",
      "    ReLU-48       [[1, 128, 2, 2]]      [1, 128, 2, 2]           0       \n",
      " MaxPool2D-11     [[1, 832, 2, 2]]      [1, 832, 2, 2]           0       \n",
      "   Conv2D-49      [[1, 832, 2, 2]]      [1, 128, 2, 2]        106,624    \n",
      "    ReLU-49       [[1, 128, 2, 2]]      [1, 128, 2, 2]           0       \n",
      "  Inception-8     [[1, 832, 2, 2]]      [1, 832, 2, 2]           0       \n",
      "   Conv2D-50      [[1, 832, 2, 2]]      [1, 384, 2, 2]        319,872    \n",
      "    ReLU-50       [[1, 384, 2, 2]]      [1, 384, 2, 2]           0       \n",
      "   Conv2D-51      [[1, 832, 2, 2]]      [1, 192, 2, 2]        159,936    \n",
      "    ReLU-51       [[1, 192, 2, 2]]      [1, 192, 2, 2]           0       \n",
      "   Conv2D-52      [[1, 192, 2, 2]]      [1, 384, 2, 2]        663,936    \n",
      "    ReLU-52       [[1, 384, 2, 2]]      [1, 384, 2, 2]           0       \n",
      "   Conv2D-53      [[1, 832, 2, 2]]      [1, 48, 2, 2]         39,984     \n",
      "    ReLU-53       [[1, 48, 2, 2]]       [1, 48, 2, 2]            0       \n",
      "   Conv2D-54      [[1, 48, 2, 2]]       [1, 128, 2, 2]        153,728    \n",
      "    ReLU-54       [[1, 128, 2, 2]]      [1, 128, 2, 2]           0       \n",
      " MaxPool2D-12     [[1, 832, 2, 2]]      [1, 832, 2, 2]           0       \n",
      "   Conv2D-55      [[1, 832, 2, 2]]      [1, 128, 2, 2]        106,624    \n",
      "    ReLU-55       [[1, 128, 2, 2]]      [1, 128, 2, 2]           0       \n",
      "  Inception-9     [[1, 832, 2, 2]]     [1, 1024, 2, 2]           0       \n",
      "   Pool2D-1      [[1, 1024, 2, 2]]     [1, 1024, 1, 1]           0       \n",
      "   Linear-1         [[1, 1024]]            [1, 10]            10,250     \n",
      "===========================================================================\n",
      "Total params: 5,835,962\n",
      "Trainable params: 5,835,962\n",
      "Non-trainable params: 0\n",
      "---------------------------------------------------------------------------\n",
      "Input size (MB): 0.00\n",
      "Forward/backward pass size (MB): 3.26\n",
      "Params size (MB): 22.26\n",
      "Estimated Total Size (MB): 25.53\n",
      "---------------------------------------------------------------------------\n",
      "\n",
      "{'total_params': 5835962, 'trainable_params': 5835962}\n"
     ]
    }
   ],
   "source": [
    "with paddle.fluid.dygraph.guard():\n",
    "    googlenet = GoogleNet(10)\n",
    "    param_info = paddle.summary(googlenet, (1, 1, 28, 28))\n",
    "    print(param_info)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## 训练模型\n",
    "\n",
    "我们使用高和宽均为96像素的图像来训练GoogLeNet模型。训练使用的图像依然来自Fashion-MNIST数据集。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Cache file /home/aistudio/.cache/paddle/dataset/mnist/train-images-idx3-ubyte.gz not found, downloading https://dataset.bj.bcebos.com/mnist/train-images-idx3-ubyte.gz \n",
      "Begin to download\n",
      "\n",
      "Download finished\n",
      "Cache file /home/aistudio/.cache/paddle/dataset/mnist/train-labels-idx1-ubyte.gz not found, downloading https://dataset.bj.bcebos.com/mnist/train-labels-idx1-ubyte.gz \n",
      "Begin to download\n",
      "........\n",
      "Download finished\n",
      "Cache file /home/aistudio/.cache/paddle/dataset/mnist/t10k-images-idx3-ubyte.gz not found, downloading https://dataset.bj.bcebos.com/mnist/t10k-images-idx3-ubyte.gz \n",
      "Begin to download\n",
      "\n",
      "Download finished\n",
      "Cache file /home/aistudio/.cache/paddle/dataset/mnist/t10k-labels-idx1-ubyte.gz not found, downloading https://dataset.bj.bcebos.com/mnist/t10k-labels-idx1-ubyte.gz \n",
      "Begin to download\n",
      "..\n",
      "Download finished\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 1/2\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/fluid/layers/utils.py:77: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working\n",
      "  return (isinstance(seq, collections.Sequence) and\n"
     ]
    }
   ],
   "source": [
    "train_dataset = paddle.vision.datasets.MNIST(mode='train')\n",
    "test_dataset = paddle.vision.datasets.MNIST(mode='test')\n",
    "# train_loader = paddle.io.DataLoader(train_dataset, places=paddle.CPUPlace(), batch_size=128, shuffle=True)\n",
    "train_loader = paddle.io.DataLoader(train_dataset, places=paddle.CUDAPlace(0), batch_size=128, shuffle=True)\n",
    "googlenet = GoogleNet()\n",
    "model = paddle.Model(googlenet)\n",
    "# 设置训练模型所需的optimizer, loss, metric\n",
    "model.prepare(\n",
    "    paddle.optimizer.Adam(learning_rate=0.001, parameters=model.parameters()),\n",
    "    paddle.nn.CrossEntropyLoss(),\n",
    "    paddle.metric.Accuracy(topk=(1, 5))\n",
    ")\n",
    "# 启动训练\n",
    "model.fit(train_dataset, epochs=2, batch_size=64, log_freq=200)\n",
    "# 启动评估\n",
    "model.evaluate(test_dataset, batch_size=64, log_freq=200)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## 小结\n",
    "\n",
    "* Inception块相当于一个有4条线路的子网络。它通过不同窗口形状的卷积层和最大池化层来并行抽取信息，并使用$1\\times 1$卷积层减少通道数从而降低模型复杂度。\n",
    "* GoogLeNet将多个设计精细的Inception块和其他层串联起来。其中Inception块的通道数分配之比是在ImageNet数据集上通过大量的实验得来的。\n",
    "* GoogLeNet和它的后继者们一度是ImageNet上最高效的模型之一：在类似的测试精度下，它们的计算复杂度往往更低。\n",
    "\n",
    "## 练习\n",
    "\n",
    "* GoogLeNet有数个后续版本。尝试实现并运行它们，然后观察实验结果。这些后续版本包括加入批量归一化层（下一节将介绍）[2]、对Inception块做调整 [3] 和加入残差连接（[“残差网络（ResNet）”](resnet.ipynb)一节将介绍）[4]。\n",
    "\n",
    "* 对比AlexNet、VGG和NiN、GoogLeNet的模型参数尺寸。为什么后两个网络可以显著减小模型参数尺寸？\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "## 参考文献\n",
    "\n",
    "[1] Szegedy, C., Liu, W., Jia, Y., Sermanet, P., Reed, S., & Anguelov, D. & Rabinovich, A.(2015). Going deeper with convolutions. In Proceedings of the IEEE conference on computer vision and pattern recognition (pp. 1-9).\n",
    "\n",
    "[2] Ioffe, S., & Szegedy, C. (2015). Batch normalization: Accelerating deep network training by reducing internal covariate shift. arXiv preprint arXiv:1502.03167.\n",
    "\n",
    "[3] Szegedy, C., Vanhoucke, V., Ioffe, S., Shlens, J., & Wojna, Z. (2016). Rethinking the inception architecture for computer vision. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (pp. 2818-2826).\n",
    "\n",
    "[4] Szegedy, C., Ioffe, S., Vanhoucke, V., & Alemi, A. A. (2017, February). Inception-v4, inception-resnet and the impact of residual connections on learning. In Proceedings of the AAAI Conference on Artificial Intelligence (Vol. 4, p. 12).\n",
    "\n",
    "## 扫码直达[讨论区](https://discuss.gluon.ai/t/topic/1662)\n",
    "\n",
    "![](../img/qr_googlenet.svg)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "PaddlePaddle 2.0.0b0 (Python 3.5)",
   "language": "python",
   "name": "py35-paddle1.2.0"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
